import React, { useEffect } from "react";
// import { useNavigate } from "react-router-dom";

import * as d3 from "d3";
import { VbpStatsByCadnI } from "../../../types";

interface PropsI {
  data: VbpStatsByCadnI[];
  watermarkText?: string;
}

const PieChartByCadnVbp: React.FC<PropsI> = (props) => {
  // const navigate = useNavigate();
  const { data, watermarkText = "" } = props;
  const refChart = React.useRef(null);
  const totalSum = d3.sum(data, (d: any) => d.amountSum);

  useEffect(() => {
    if (refChart && refChart.current && data && data.length > 0) {
      const node = refChart.current;

      // 设定svg元素所占面积
      const margin = { top: 50, right: 130, bottom: 30, left: 380 };
      const width = 1024;
      const height = 1024;
      // 设定四周边距

      d3.select(node).selectAll("svg").remove();
      var svg = d3
        .select(node)
        .append("svg")
        .attr("width", width)
        .attr("height", height)
        .attr("viewBox", [0, 0, width, height]) // 后续rect等图是相对viewBox计算的，viewBox可随svg绽放
        .attr("style", "max-width: 100%; height: auto;");

      // Create the color scale.
      const colorScale = d3
        .scaleOrdinal()
        .domain(data.map((d: any) => d.deptYbName))
        .range(
          d3
            .quantize((t) => d3.interpolateSpectral(t * 0.8 + 0.1), data.length)
            .reverse()
        );

      // Create the pie layout and arc generator.
      const pie = d3
        .pie()
        .sort(null)
        .value((d: any) => d.amountSum);

      const arc = d3
        .arc()
        .innerRadius(0)
        .outerRadius(Math.min(width, height) / 3 - 1);
      // console.log(arc.outerRadius());
      // console.log((arc.outerRadius() as any)());

      const labelRadius = (arc.outerRadius() as any)() * 0.8;

      // A separate arc generator for labels.
      const arcLabel = d3.arc().innerRadius(200).outerRadius(300);

      // 用pie函数加工原始数据，生成始末角度等数值
      const arcs = pie(data as any);
      // console.log(arcs);

      svg
        .append("g")
        .attr("stroke", "white")
        .selectAll()
        .data(arcs)
        .join("path")
        .attr("transform", `translate(${width / 2}, ${height / 2})`)
        .attr("fill", (d: any) => colorScale(d.data.deptYbName) as any)
        .attr("d", arc as any)
        .append("title")
        .text((d: any) => {
          // console.log(d);
          return d.data.deptYbName;
        });

      // Create a new arc generator to place a label close to the edge.
      // The label shows the value if there is enough room.
      console.log(arcs);
      svg
        .append("g")
        .attr("transform", `translate(${width / 2}, ${height / 2})`)
        .attr("text-anchor", "middle")
        .selectAll()
        .data(
          arcs.filter((item: any) => {
            return item.endAngle - item.startAngle > 0.2;
          })
        )
        .join("text")
        .attr("transform", (d: any) => {
          // console.log(d);
          // console.log(arcLabel.centroid(d));
          return `translate(${arcLabel.centroid(d)})`;
        })
        .call((text) =>
          text
            .append("tspan")
            .attr("y", "-0.4em")
            .attr("font-weight", "bold")
            .text((d: any) => d.data.deptYbName)
        )
        .call((text) =>
          text
            .filter((d) => d.endAngle - d.startAngle > 0.25)
            .append("tspan")
            .attr("x", 0)
            .attr("y", "0.7em")
            .attr("fill-opacity", 0.7)
            .text((d: any) => {
              return `${d.data.amountSum}, 占比${(
                (d.data.amountSum / totalSum) *
                100
              ).toFixed(2)}%`;
            })
        );
    }

    // 清除副作用
    return () => {
      d3.select(refChart.current).selectAll("*").remove();
    };
  }, [data]);

  return (
    <div>
      <div ref={refChart}></div>
    </div>
  );
};

export default PieChartByCadnVbp;
